// Author: combacsa@kaist.ac.kr
// http://www.jungol.co.kr/prog/Hanal/hanalView.php?qs_code=

//#define COMPILE_P2567
#ifdef COMPILE_P2567

#include <fstream>

using namespace std;

int main() {
	int n, m, p, i, j;

	ifstream in("input.txt");
	in >> n >> p;
	in.close();
	
	int cycle[1001];
	for (i = 0; i <= (n > p ? n : p); i++) {
		cycle[i] = 0;
	}

	m = n;

	for (j = 1; cycle[n] == 0; j++, n = (n * m) % p) {
		cycle[n] = j;
	}

	ofstream out("output.txt");
	out << j - cycle[n] << "\n";
	out.close();
	return 0;
}

#endif
